<template>
<div class="home">
  <div id="container"></div>
  <div class="info-box">
      <!-- <span style="margin: 5px 8px;" ref="infoWind">
        经纬度：<span class="copy" style="cursor: pointer;">{{longitude + ',' + latitude}}</span>
      </span> -->
    <el-select v-model="keyword" show-search placeholder="请输入关键字搜索" style="width: 300px" filterable remote reserve-keyword :remote-method="handleSearch">
      <el-option v-for="item in data" :key="item.id" :value="item.id" :label="item.name" @click="handleSelect(item)">
        <div class="d-flex flex-column">
          <span>{{item.name}}</span>
          <span style="font-size: '10px'; color: #999999">{{item.address}}</span>
        </div>
      </el-option>
    </el-select>

  </div>
</div>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
  securityJsCode: '10136cc722767f185da332d3c96e827b'
}
import { watch, ref, reactive, onBeforeMount, toRefs, computed, onMounted } from 'vue';
const props = defineProps({
  // detailedAddress、longitude、latitude
  pointDetail: {
    type: Object,
    default: () => {},
  },
});
 // 地图实例
const customMap = ref(null)
// 标记点实例
// const marker = ref(null)
// 搜索关键字
const keyword = ref(null);
// 搜索的详细地址
const detailAddress = ref(null)
// 下拉搜索的data数据
const data = ref([]);
// 经度
const longitude = ref('')
// 纬度
const latitude = ref('')
const isEcho = ref(false)
const emit = defineEmits(['addressDetail']);
// const coord = ref('');
let AMapObj, placeSearch, geocoder,marker,infoWindow;

// coord.value =  props.pointDetail.longitude + ',' + props.pointDetail.latitude
const infoWind = ref(null)
const initMap = () => {
    AMapLoader.load({
        key:"4b35dc8af56ae2a9628ef042307654ff", // 申请好的Web端开发者Key，首次调用 load 时必填
        // key:"f9dec1cff64a6d74a2189f62a9086a6f", // 申请好的Web端开发者Key，首次调用 load 时必填
        version:"2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins:['AMap.Marker','AMap.ToolBar','AMap.Driving'],  // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        AMapUI: {
          // 是否加载 AMapUI，缺省不加载
          version: "1.1", // AMapUI 缺省 1.1
          plugins: [], // 需要加载的 AMapUI ui插件
        }
    }).then((AMap)=>{
      AMapObj = AMap
        customMap.value = new AMap.Map("container",{  //设置地图容器id
            viewMode:"2D",    //是否为3D地图模式
            zoom:11,           //初始化地图级别
            center:[props.pointDetail.longitude,props.pointDetail.latitude], //初始化地图中心点位置
        });
        customMap.value.addControl(new AMap.Marker())

        // 画一个可拖拽的点位
        // handlePositionPickerEvent()
        // 给地图添加点击事件
        // customMap.value.on('click',onMapClick);
        AMap.plugin(
          ['AMap.ToolBar','AMap.Scale','AMap.Geolocation','AMap.PlaceSearch',
        'AMap.Geocoder','AMap.AutoComplete','AMap.InfoWindow'],
        () => {
          // 缩放条
          const toolbar = new AMap.ToolBar();
          // 比例尺
          const scale = new AMap.Scale();
          // 定位
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认:true
            timeout: 10000, // 超过10秒后停止定位，默认：5s
            position: 'RT', // 定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
          });
          geocoder = new AMap.Geocoder({
            city: '全国',
          });
          infoWindow = new AMap.InfoWindow({
            isCustom: true,  //使用自定义窗体
            // content: createInfoWindow(title, content.join("<br/>")),
            content: 123,
            offset: new AMap.Pixel(16, -45)
          })          
          customMap.value.addControl(geolocation);
          customMap.value.addControl(toolbar);
          customMap.value.addControl(scale);
          customMap.value.addControl(infoWindow)
          placeSearch = new AMap.PlaceSearch({
            city: '全国',
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            citylimit: false, // 是否强制限制在设置的城市内搜索
            autoFitView: true,
          });
          // 判断是否要回显点位
          if(isEcho.value) {
            editMap()
          }
        }
        )
    }).catch(e=>{
        console.log(e);
    })
}
const showMaeker = () => {
  isEcho.value = true
}
const positionPicker = ref(null)
// 实现拖拽选址功能
const handlePositionPickerEvent = () => {
     AMapUI.loadUI(["misc/PositionPicker"], (PositionPicker) =>{
        console.log("拖拽加载成功");
        positionPicker.value = new PositionPicker({
          // mode: 'dragMap',//拖拽地图
          mode: "dragMarker",//拖拽图标
          map: customMap.value,
        });
        infoWindow.close()
        positionPicker.value.on("success", (positionResult)=> {
          if(positionResult.address){
            // keyword.value = positionResult.address
            detailAddress.value = positionResult.address
            longitude.value = positionResult.position.lng
            latitude.value = positionResult.position.lat
          }else{
            // keyword.value = '暂无数据'
            detailAddress.value = '暂无数据'
            longitude.value = '——'
            latitude.value = '——'
          };
          // 添加信息提示框
          let item = {
            address: detailAddress.value,
            latitude: latitude.value,
            longitude: longitude.value
          }
          console.log('走到这里了');
          
          emit('addressDetail',item)
          addInfoWindow(item)
        });
        positionPicker.value.on("fail", (positionResult) =>{
          // 海上或海外无法获得地址信息
          console.log(positionResult,'拖拽失败的结果positionResult');
        });
        positionPicker.value.on('click',function(){
          console.log('12313');
          
        })
        // 初始的时候释放点位
        positionPicker.value.start()

      });
}
// 回显的方法
const editMap = () => {
  // 页面刚进来的时候
  // keyword.value = props.pointDetail.detailedAddress
  // 经度赋值
  longitude.value = props.pointDetail.longitude
  // 纬度赋值
  latitude.value = props.pointDetail.latitude
  // 赋值之后调用标点方法
  let obj = {
    lng: props.pointDetail.longitude,
    lat: props.pointDetail.latitude
  }
  // drawMarker(obj)
  handlePositionPickerEvent([props.pointDetail.longitude,props.pointDetail.latitude])
//  addInfoWindow()
  isEcho.value = false
}
// 搜索地图
const handleSearch = (str) => {
  placeSearch.search(str, (status, result) => {
    console.log(result);
    if (result && typeof result === 'object' && result.poiList) {
      const list = result.poiList.pois;
      list.forEach(item => {
        item.value = item.name;
        item.label = item.name;
      });
      data.value = list
    }
  });
}
// 点击地图
const onMapClick = (e) => {
    // coord.value = e.lnglat.lng + ',' + e.lnglat.lat
    longitude.value = e.lnglat.lng
    latitude.value = e.lnglat.lat
  geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // result为对应的地理位置详细信息
      keyword.value = result.regeocode.formattedAddress
    }
  })
  drawMarker(e.lnglat)
}
// 点击搜索项
const handleSelect = (item) => {
  console.log(item);
  // drawMarker(item.location)
  let obj = {
    lng: item.location.lng,
    lat: item.location.lat
  }
  console.log(obj,'obj');
  
  positionPicker.value.start([item.location.lng,item.location.lat])

  if (item.location != null) {
    // coord.value = item.location.lng + ',' + item.location.lat
    longitude.value = item.location.lng
    latitude.value = item.location.lat
  }
}
// 绘制地点marker
const drawMarker = (location) => {
 if (location == null) return
  let longitude = location.lng, latitude = location.lat
  if (marker) {
    marker.setMap(null);
  }
  marker = new AMapObj.Marker({
    position: new AMapObj.LngLat(longitude, latitude),
    draggable: true,
    anchor: 'bottom-center',
  });
  marker.on('click', () => {
    // coord.value = location;
    console.log(location,'location');
    
  })
  customMap.value.add(marker);
  customMap.value.setZoomAndCenter(16, [longitude, latitude]);
}


const addMarker = () => {
    // 添加标记点
    marker = new AMap.Marker({
        // position: customMap.value.getCenter(),
        position: [props.pointDetail.longitude,props.pointDetail.latitude],
        // position: new AMap.LngLat(120.152925,30.248748), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        icon: new AMap.Icon({
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          imageSize: new AMap.Size(25, 36),
        }),
        // 偏移的距离要是icon尺寸的一半
        offset: new AMap.Pixel(-12.5, -18),
        // 设置是否可以拖拽
        draggable: true,
        cursor: 'move',
    });
    marker.setMap(customMap.value)
} 
const addInfoWindow = (item) => {
  // const item = {
  //   content: '浙江省杭州市西湖区西湖文化广场浙江省杭州市西湖区西湖文化广场',
  //   latitude: latitude.value,
  //   longitude: longitude.value
  // }
  let content = [
      `<div style="background-color: white; color: black; padding: 10px; border-radius: 5px; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);">`,
      `<b>位置信息</b><br/>`,
      `经度 : ${item.longitude}<br/>`,
      `纬度 : ${item.latitude}<br/>`,
      `地址 : ${item.address}`,
      `</div>`
  ];
       // 创建 infoWindow 实例	
      infoWindow = new AMap.InfoWindow({
        isCustom: true,  //使用自定义窗体
        // content: createInfoWindow(title, content.join("<br/>")),
        content: content.join(''),
        offset: new AMap.Pixel(16, -45)
      })   
      // 打开信息窗体
      let dd = customMap.value.getCenter()
      // dd.pos = [e.pos[0], e.pos[1]]
      dd.lat = item.latitude
      dd.lng = item.longitude
      console.log(dd,'dd')
      infoWindow.open(customMap.value, dd);
}
onMounted(() => {
  initMap()
})
defineExpose({
  showMaeker,
});
</script>

<style lang="scss" scoped>
.home {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
  position: relative;
  .info-box {
      position: absolute;
    top: 8px;
    right: 8px;
    width: 300px;
    // background-color: #1f1f1f;
    background: #ffffff;
    display: flex;
    flex-direction: column;
  }
}
#container {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}
</style>